package com.zzh.camera2.ui

import android.graphics.ImageFormat
import android.os.Build
import android.os.Bundle
import android.util.Log
import com.zzh.camera2.R
import com.zzh.camera2.manager.*
import com.zzh.camera2.manager.IUvcCameraManager.UvcCameraManagerHost
import com.zzh.camera2.permission.PermissionCheckUtil
import kotlinx.android.synthetic.main.activity_uvccamera.*


class UvcCameraActivity : BaseActivity(), UvcCameraManagerHost, ICameraPreviewCallback {
    companion object {
        const val TAG = "UvcCameraActivity"
    }

    lateinit var uvcCameraManager: IUvcCameraManager

    // for ir/dot camera @{
    lateinit var cameraManager: ICameraManager
    // @}

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_uvccamera)

        // if permission no granted, then to grant permission view
        if (!PermissionCheckUtil.checkAllPermissions(this)) {
            PermissionCheckUtil.requestAllPermissions(this)
            return
        }
        initUvcCameraManager()
        initCameraManager()
    }

    private fun initUvcCameraManager() {
        uvcCameraManager = UvcCameraManager()
        uvcCameraManager.setHost(this)
        uvcCameraManager.initUVCCamera(textureView2, this.applicationContext)
    }

    private fun initCameraManager() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            cameraManager = CameraApi1Manager()
        } else {
            cameraManager = CameraApi2Manager(this)
        }
        cameraManager.setPreviewCallback(this)
    }

    override fun onResume() {
        super.onResume()
        cameraManager.openCamera(textureView1, 0, 1280, 720, ImageFormat.YUV_420_888)
        cameraManager.startPreview()
//        Handler(Looper.getMainLooper()).postDelayed(Runnable {
        uvcCameraManager.switchUVCPreview(true)
//        }, 0)
    }

    override fun onPause() {
        super.onPause()
        uvcCameraManager.switchUVCPreview(false)
//        Handler(Looper.getMainLooper()).postDelayed({
        cameraManager.stopPreview()
        cameraManager.releaseCamera()
//        }, 0)
    }

    override fun onDestroy() {
        super.onDestroy()
        uvcCameraManager.closeUVCCamera()
    }

    // uvc camera preview data call back
    override fun onUvcPreviewCallback(data: ByteArray?) {
        Log.i(TAG, "onUvcPreviewCallback data=$data")
    }

    // use android camera api1/2 camera preview data call back
    override fun onPreviewFrame(
        data: ByteArray?,
        convertedImageFormat: Int,
        cameraManager: ICameraManager
    ) {
        Log.i(
            TAG,
            "onPreviewCallback data=$data, convertedImageFormat=$convertedImageFormat, cameraManager=$cameraManager"
        )
        if (data?.count()!! > 1) {
            Log.i(TAG, "onUvcPreviewCallback data[0]=" + data.get(0) + ", data[1]=" + data.get(1))
        }
    }
}